package com.wing.wecom.service;

import chat.qiye.wechat.sdk.api.contact.ContactDeptApi;
import chat.qiye.wechat.sdk.api.contact.resp.ContactDeptListResp;
import chat.qiye.wechat.sdk.api.contact.vo.ContactDeptVo;
import chat.qiye.wechat.sdk.common.RespStatus;
import chat.qiye.wechat.sdk.constant.AppTypeEnum;
import chat.qiye.wechat.sdk.service.ApiConfigurationDefaultProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 企业微信部门-ContactUserServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class DeptServiceImpl implements DeptService {

    @Resource
    ContactDeptApi contactDeptApi;
    @Resource
    ApiConfigurationDefaultProvider apiConfigurationDefaultProvider;

    @Override
    public ContactDeptListResp list(Integer id) {
        return contactDeptApi.list(id);
    }

    @Override
    public int create(ContactDeptVo contactDeptVo) {
        RespStatus respStatus = contactDeptApi.create(contactDeptVo);
        if(respStatus.getErrcode() == 42001){ // access_token已过期
            apiConfigurationDefaultProvider.loadAppToken(AppTypeEnum.APP_CONTACT.getAppId());
            respStatus = contactDeptApi.create(contactDeptVo);
        }
        return respStatus.success() ? 1 : 0;
    }

    @Override
    public int update(ContactDeptVo contactDeptVo) {
        RespStatus respStatus = contactDeptApi.update(contactDeptVo);
        if(respStatus.getErrcode() == 42001){ // access_token已过期
            apiConfigurationDefaultProvider.loadAppToken(AppTypeEnum.APP_CONTACT.getAppId());
            respStatus = contactDeptApi.update(contactDeptVo);
        }
        return respStatus.success() ? 1 : 0;
    }

    @Override
    public int delete(Integer id) {
        RespStatus respStatus = contactDeptApi.delete(id);
        if(respStatus.getErrcode() == 42001){ // access_token已过期
            apiConfigurationDefaultProvider.loadAppToken(AppTypeEnum.APP_CONTACT.getAppId());
            respStatus = contactDeptApi.delete(id);
        }
        return respStatus.success() ? 1 : 0;
    }

}
